package com.ruoyi.web.controller.topic;


import com.ruoyi.system.domain.Type;
import com.ruoyi.system.domain.vo.Result;
import com.ruoyi.system.service.TypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@RestController
@Api(tags = "分类模块")
@RequestMapping("/api")
public class TypeController {

    @Autowired
    private TypeService typeService;

    @ApiOperation("获得所有分类")
    @GetMapping("/types")
    public Result<List<Type>> getAllType(){
        List<Type> allTypeQuery = typeService.getAllTypeQuery();
        return Result.success(allTypeQuery);
    }

    @ApiOperation("根据id获取分类")
    @GetMapping("/types/id/{id}")
    public Result<Type> getTypeById(@PathVariable("id") Long id){
        return Result.success(typeService.getTypeById(id));
    }

    @ApiOperation("根据name获取分类")
    @GetMapping("/types/name/{name}")
    public Result<Type> getTypeByName(@PathVariable("name") String name){
        return Result.success(typeService.getTypeByName(name));
    }

    @ApiOperation("添加分类")
    @PostMapping("/types/input")
    public Result<?> addTypes(Type type, RedirectAttributes attributes){
        Type typeOne = typeService.getTypeByName(type.getName());
        if(typeOne != null){
            attributes.addFlashAttribute("message","不能添加重复分类");
            /*return "redirect:/admin/types";*/
            Result.fail("添加失败，已存在重复类型");
        }

        int t = typeService.saveType(type);
        if(t==0){
            attributes.addFlashAttribute("message","新增失败");
        }
        else {
            attributes.addFlashAttribute("message","新增成功");
        }
        return Result.success();
    }

    @ApiOperation("修改分类")
    @PostMapping("/types/{id}")
    public Result<?> updateTypes(Type type,@PathVariable("id") Long id,RedirectAttributes attributes){
        Type typeOne = typeService.getTypeByName(type.getName());
        if(typeOne != null){
            Result.fail("修改失败，已存在重复类型");
        }
        int t = typeService.updateType(type);
        if(t==0){
            attributes.addFlashAttribute("message","新增失败");
        }
        else {
            attributes.addFlashAttribute("message","新增成功");
        }
        return Result.success();
    }

    @ApiOperation("删除分类")
    @PostMapping("/types/{id}/delete")
    public Result<?> deleteTypes(@PathVariable("id") Long id){
        typeService.deleteType(id);
        return Result.success();
    }


}
